package com.shxc.smarttrade.kvb.fragment;

import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.text.style.ForegroundColorSpan;
import android.view.Gravity;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.shxc.smarttrade.R;
import com.shxc.smarttrade.base.BaseFragment;
import com.shxc.smarttrade.currency.model.CurrencyModel;
import com.shxc.smarttrade.dialog.PhotoDialog;
import com.shxc.smarttrade.info.Contents;
import com.shxc.smarttrade.kvb.activity.KvbOpenAccountActivity;
import com.shxc.smarttrade.kvb.model.OpenKVBModel;
import com.shxc.smarttrade.utils.analysis.JsonAnalysisModel;
import com.shxc.smarttrade.utils.analysis.JsonAnalysisUtils;
import com.shxc.smarttrade.utils.AppUtils;
import com.shxc.smarttrade.utils.GlideImageLoader;
import com.shxc.smarttrade.utils.GlideUtils;
import com.shxc.smarttrade.utils.IdcardUtils;
import com.shxc.smarttrade.utils.Loger;
import com.shxc.smarttrade.utils.MyOkHttpUtils;
import com.shxc.smarttrade.utils.PhoneFormatCheckUtils;
import com.shxc.smarttrade.utils.ToastUtils;
import com.yancy.gallerypick.config.GalleryConfig;
import com.yancy.gallerypick.config.GalleryPick;
import com.yancy.gallerypick.inter.IHandlerCallBack;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.xchris.view.annotation.ContentView;
import org.xchris.view.annotation.Event;
import org.xchris.view.annotation.ViewInject;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;

/**
 * KVB开户 一.填写注册资料
 */
@ContentView(R.layout.fragment_kvb_1)
public class KvbOpen1Fragment extends BaseFragment {

    String notice = "身份证信息将通过中国公民身份证号码中心验证。为了您的资金安全，请填写真实信息，我们不会以任何方式泄漏";

    @ViewInject(R.id.notice_textview)
    TextView notice_textview;//提示

    @ViewInject(R.id.phone_view)
    View phone_view;//手机号
    @ViewInject(R.id.phone_edittext)
    EditText phone_edittext;//手机号
    @ViewInject(R.id.get_code_textview)
    TextView get_code_textview;//获取验证码
    @ViewInject(R.id.phone_warning)
    View phone_warning;

    @ViewInject(R.id.code_view)
    View code_view;//验证码
    @ViewInject(R.id.code_edittext)
    EditText code_edittext;
    @ViewInject(R.id.code_warning)
    View code_warning;

    @ViewInject(R.id.id_name_view)
    View id_name_view;//身份证姓名
    @ViewInject(R.id.id_name_edittext)
    EditText id_name_edittext;
    @ViewInject(R.id.id_name_warning)
    View id_name_warning;

    @ViewInject(R.id.id_number_view)
    View id_number_view;//身份证号码
    @ViewInject(R.id.id_number_edittext)
    EditText id_number_edittext;
    @ViewInject(R.id.id_number_warning)
    View id_number_warning;

    @ViewInject(R.id.id_front_view)
    View id_front_view;//身份证正面
    @ViewInject(R.id.id_front_textview)
    TextView id_front_textview;
    @ViewInject(R.id.id_front_imageview)
    ImageView id_front_imageview;
    @ViewInject(R.id.id_front_warning)
    View id_front_warning;

    @ViewInject(R.id.id_back_view)
    View id_back_view;//身份证背面
    @ViewInject(R.id.id_back_textview)
    TextView id_back_textview;
    @ViewInject(R.id.id_back_imageview)
    ImageView id_back_imageview;
    @ViewInject(R.id.id_back_warning)
    View id_back_warning;

    @ViewInject(R.id.email_view)
    View email_view;//电子邮箱
    @ViewInject(R.id.email_edittext)
    EditText email_edittext;
    @ViewInject(R.id.email_warning)
    View email_warning;

    @ViewInject(R.id.address_view)
    View address_view;//地址
    @ViewInject(R.id.address_edittext)
    EditText address_edittext;
    @ViewInject(R.id.address_warning)
    View address_warning;

    @ViewInject(R.id.pass_view)
    View pass_view;//登录密码
    @ViewInject(R.id.pass_edittext)
    EditText pass_edittext;
    @ViewInject(R.id.visible_imageview)
    ImageView visible_imageview;
    @ViewInject(R.id.pass_warning)
    View pass_warning;

    private KvbOpenAccountActivity kvbOpenAccountActivity;

    private String telephone;//手机号
    private String name;//身份证姓名
    private String identity; //身份证号
    private String smsCode;//短信验证码
    private String email;//邮箱
    private String address;//通讯地址
    private String password;//密码
    private String frontImg;//正面照片
    private String backImg;//反面照片
    private String frontName;
    private String backName;

    int photoOrder = 0;

    private PhotoDialog photoDialog;

    private MyCountDownTimer timer;

    private GlideUtils glideUtils;

    private boolean canSee = false;


    @Event({R.id.get_code_textview, R.id.id_front_imageview, R.id.id_back_imageview, R.id.next_button, R.id.visible_imageview})
    private void onClick(View view) {

        switch (view.getId()) {
            case R.id.get_code_textview:
                //获取验证码
                telephone = phone_edittext.getText().toString().trim();
                //验证手机号
                if (!PhoneFormatCheckUtils.isChinaPhoneLegal(telephone)) {
                    phone_view.setBackgroundResource(R.drawable.box_kvb_red);
                    phone_warning.setVisibility(View.VISIBLE);
                } else {
                    phone_view.setBackgroundResource(R.drawable.box_kvb_blue);
                    phone_warning.setVisibility(View.INVISIBLE);
                    timer.start();
                    getCode();
                }
                break;
            case R.id.id_front_imageview:
                //身份证正面
                photoOrder = 1;
                photoDialog.show();
                photoDialog.getPhoto_textview().setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        initPermissions2();
                        photoDialog.dismiss();
                    }
                });
                photoDialog.getAlbum_textview().setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        initPermissions();
                        photoDialog.dismiss();
                    }
                });
                photoDialog.getCancel_texxtview().setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        photoDialog.dismiss();
                    }
                });
                break;
            case R.id.id_back_imageview:
                //身份证背面
                photoOrder = 2;
                photoDialog.show();
                photoDialog.getPhoto_textview().setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        initPermissions2();
                        photoDialog.dismiss();
                    }
                });
                photoDialog.getAlbum_textview().setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        initPermissions();
                        photoDialog.dismiss();
                    }
                });
                photoDialog.getCancel_texxtview().setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        photoDialog.dismiss();
                    }
                });
                break;
            case R.id.next_button:
                //下一步
                CheckInfo();
                break;
            case R.id.visible_imageview:
                canSee = !canSee;
                if (canSee) {
                    visible_imageview.setImageResource(R.mipmap.xianshi_icon);
                    pass_edittext.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                } else {
                    visible_imageview.setImageResource(R.mipmap.yingcang_icon);
                    pass_edittext.setTransformationMethod(PasswordTransformationMethod.getInstance());
                }
                break;
        }
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        initView();
        initGallery();
    }

    private void initView() {

        kvbOpenAccountActivity = (KvbOpenAccountActivity) getActivity();

        glideUtils = new GlideUtils(getActivity());

        timer = new MyCountDownTimer(60000, 1000);

        //设置提示文字
        SpannableString spannableString = new SpannableString(notice);
        spannableString.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.kvb_account)), 8, 19, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        notice_textview.setText(spannableString);

        photoDialog = new PhotoDialog(getActivity(),
                getResources().getIdentifier("BottomDialog", "style", getActivity().getPackageName()));
        photoDialog.getWindow().setGravity(Gravity.BOTTOM | Gravity.LEFT | Gravity.RIGHT);
        photoDialog.setCanceledOnTouchOutside(false);
    }

    //检验数据
    private void CheckInfo() {
        telephone = phone_edittext.getText().toString().trim();
        smsCode = code_edittext.getText().toString().trim();
        name = id_name_edittext.getText().toString().trim();
        identity = id_number_edittext.getText().toString().trim();
        email = email_edittext.getText().toString().trim();
        address = address_edittext.getText().toString().trim();
        password = pass_edittext.getText().toString().trim();

        int error = 0;

        //验证手机号
        if (PhoneFormatCheckUtils.isChinaPhoneLegal(telephone)) {
            phone_view.setBackgroundResource(R.drawable.box_kvb_blue);
            phone_warning.setVisibility(View.INVISIBLE);
        } else {
            error++;
            phone_view.setBackgroundResource(R.drawable.box_kvb_red);
            phone_warning.setVisibility(View.VISIBLE);
        }

        //验证码
        if (AppUtils.isEmpty(smsCode) || !AppUtils.isNumeric(smsCode) || smsCode.length() != 6) {
            error++;
            code_view.setBackgroundResource(R.drawable.box_kvb_red);
            code_warning.setVisibility(View.VISIBLE);
        } else {
            code_view.setBackgroundResource(R.drawable.box_kvb_blue);
            code_warning.setVisibility(View.INVISIBLE);
        }

        //身份证姓名
        if (AppUtils.isEmpty(name) || name.length() < 2) {
            error++;
            id_name_view.setBackgroundResource(R.drawable.box_kvb_red);
            id_name_warning.setVisibility(View.VISIBLE);
        } else {
            id_name_view.setBackgroundResource(R.drawable.box_kvb_blue);
            id_name_warning.setVisibility(View.INVISIBLE);
        }

        //身份证号码
        if (AppUtils.isEmpty(identity) || !IdcardUtils.isNum(identity)) {
            error++;
            id_number_view.setBackgroundResource(R.drawable.box_kvb_red);
            id_number_warning.setVisibility(View.VISIBLE);
        } else {
            id_number_view.setBackgroundResource(R.drawable.box_kvb_blue);
            id_number_warning.setVisibility(View.INVISIBLE);
        }

        //身份证正面
        if (AppUtils.isEmpty(frontImg)) {
            error++;
            id_front_view.setBackgroundResource(R.drawable.box_kvb_red);
            id_front_warning.setVisibility(View.VISIBLE);
        } else {
            id_front_view.setBackgroundResource(R.drawable.box_kvb_blue);
            id_front_warning.setVisibility(View.INVISIBLE);
        }

        //身份证背面
        if (AppUtils.isEmpty(backImg)) {
            error++;
            id_back_view.setBackgroundResource(R.drawable.box_kvb_red);
            id_back_warning.setVisibility(View.VISIBLE);
        } else {
            id_back_view.setBackgroundResource(R.drawable.box_kvb_blue);
            id_back_warning.setVisibility(View.INVISIBLE);
        }

        //电子邮箱
        if (AppUtils.isEmpty(email) || !AppUtils.isEmail(email)) {
            error++;
            email_view.setBackgroundResource(R.drawable.box_kvb_red);
            email_warning.setVisibility(View.VISIBLE);
        } else {
            email_view.setBackgroundResource(R.drawable.box_kvb_blue);
            email_warning.setVisibility(View.INVISIBLE);
        }

        //地址
        if (AppUtils.isEmpty(address)) {
            error++;
            address_view.setBackgroundResource(R.drawable.box_kvb_red);
            address_warning.setVisibility(View.VISIBLE);
        } else {
            address_view.setBackgroundResource(R.drawable.box_kvb_blue);
            address_warning.setVisibility(View.INVISIBLE);
        }

        //密码
        if (password.length() < 6 || password.length() > 16 || AppUtils.isNumeric(password)|| password.matches("^[a-zA-Z]*")) {
            error++;
            pass_view.setBackgroundResource(R.drawable.box_kvb_red);
            pass_warning.setVisibility(View.VISIBLE);
        } else {
            pass_view.setBackgroundResource(R.drawable.box_kvb_blue);
            pass_warning.setVisibility(View.INVISIBLE);
        }
        if (error == 0) {
            checkCode();
        } else {
            ToastUtils.showToast("请重新核实开户信息");
        }
    }

    private GalleryConfig galleryConfig;
    private IHandlerCallBack iHandlerCallBack;
    private List<String> path = new ArrayList<>();

    //初始化图库
    private void initGallery() {

        iHandlerCallBack = new IHandlerCallBack() {
            @Override
            public void onStart() {
                Loger.e("initGallery", "onStart: 开启");
            }

            @Override
            public void onSuccess(List<String> photoList) {
                Loger.e("initGallery", "onSuccess: 返回数据");
                path.clear();
                for (String s : photoList) {
                    Loger.e("initGallery", s);
                    path.add(s);
                }
                for (int i = 0; i < path.size(); i++) {
                    Loger.e("path：", path.get(i));
                }
                //TODO 得到返回数据
                switch (photoOrder) {
                    case 1:
                        frontImg = path.get(0);
                        String[] ss1 = frontImg.split("/.");
                        frontName = ss1[ss1.length - 1];
                        Loger.e("frontName", frontName);
                        glideUtils.showImage(frontImg, id_front_imageview);
                        id_front_textview.setText("已上传");
                        break;
                    case 2:
                        backImg = path.get(0);
                        String[] ss2 = backImg.split("/.");
                        backName = ss2[ss2.length - 1];
                        Loger.e("backName", backName);
                        glideUtils.showImage(backImg, id_back_imageview);
                        Loger.e("backImg", backImg);
                        id_back_textview.setText("已上传");
                        break;
                }
            }

            @Override
            public void onCancel() {
                Loger.e("initGallery", "onCancel: 取消");
            }

            @Override
            public void onFinish() {
                Loger.e("initGallery", "onFinish: 结束");
            }

            @Override
            public void onError() {
                Loger.e("initGallery", "onError: 出错");
            }
        };
        galleryConfig = new GalleryConfig.Builder()
                .imageLoader(new GlideImageLoader())    // ImageLoader 加载框架（必填）
                .iHandlerCallBack(iHandlerCallBack)     // 监听接口（必填）
                .provider("com.shxc.smarttrade.fileprovider")   // provider(必填)
                .pathList(path)                         // 记录已选的图片
                .multiSelect(false)                      // 是否多选   默认：false
                .multiSelect(false, 1)                   // 配置是否多选的同时 配置多选数量   默认：false ， 9
                .maxSize(1)                             // 配置多选时 的多选数量。    默认：9
                .crop(false)                             // 快捷开启裁剪功能，仅当单选 或直接开启相机时有效
                .crop(true, 1, 1, 512, 512)             // 配置裁剪功能的参数，   默认裁剪比例 1:1
                .isShowCamera(false)                     // 是否现实相机按钮  默认：false
                .filePath("/SmartTrade/Pictures")          // 图片存放路径
                .build();
    }

    private final int PERMISSIONS_REQUEST_READ_CONTACTS = 8;
    private final int PERMISSIONS_REQUEST_CAMERA = 9;

    // 授权管理 - 相册
    private void initPermissions() {
        if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                ToastUtils.showToast("请在 setting-应用管理 中开启此应用的储存授权。");
            } else {
                ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, PERMISSIONS_REQUEST_READ_CONTACTS);
            }
        } else {
            GalleryPick.getInstance().setGalleryConfig(galleryConfig).open(getActivity());
        }
    }

    // 授权管理 - 相机
    private void initPermissions2() {
        if (Build.VERSION.SDK_INT >= 23) {
            int checkCallPhonePermission = ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.CAMERA);
            if (checkCallPhonePermission != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.CAMERA}, PERMISSIONS_REQUEST_CAMERA);
                return;
            } else {
                GalleryPick.getInstance().setGalleryConfig(galleryConfig).openCamera(getActivity());
            }
        } else {
            GalleryPick.getInstance().setGalleryConfig(galleryConfig).openCamera(getActivity());
        }
    }

    // 授权返回
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], @NonNull int[] grantResults) {

        switch (requestCode) {
            case PERMISSIONS_REQUEST_READ_CONTACTS:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    Loger.e("initPermissions", "同意授权");
                    //
                    GalleryPick.getInstance().setGalleryConfig(galleryConfig).open(getActivity());
                } else {
                    Loger.e("initPermissions", "拒绝授权");
                }
                break;
            case PERMISSIONS_REQUEST_CAMERA:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // Permission Granted
                    //
                    GalleryPick.getInstance().setGalleryConfig(galleryConfig).openCamera(getActivity());
                } else {
                    // Permission Denied
                    ToastUtils.showToast("很遗憾你把相机权限禁用了。请务必开启相机权限享受我们提供的服务吧。");
                }
                break;
            default:
                super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (photoDialog.isShowing()) {
            photoDialog.dismiss();
        }
    }

    //获取短信验证码
    private void getCode() {
        loadingDialog.show();
        Map<String, Object> map = new HashMap<>();
        map.put("telephone", telephone);
        map.put("accessToken", "d31303049b7224712b2073354d4cc92c8a196f1894b1876509d78b4cd9268149b9ab165da9a31a6251d2448261fd99d1a7d22133bb3ef018493849f4a7896993");

        MyOkHttpUtils.getServiceDatas(map, Contents.KVB_GETSMSCODE, new MyOkHttpUtils.ServiceStatus() {
            @Override
            public void success(String response, int d) {
                if (response != null) {
                    JsonAnalysisModel jam = JsonAnalysisUtils.jsonAnalysis(response, CurrencyModel.class);
                    if (jam.isSuccess()) {

                    } else {
                        ToastUtils.showToast("获取验证码失败");
                    }
                }
                loadingDialog.dismiss();
            }

            @Override
            public void faild(Call call, Exception e, int id) {
                loadingDialog.dismiss();
            }
        });
    }

    //初步验证短信验证码
    private void checkCode() {
        loadingDialog.show();
        Map<String, Object> map = new HashMap<>();
        map.put("telephone", telephone);
        map.put("code", smsCode);
        map.put("accessToken", "d31303049b7224712b2073354d4cc92c8a196f1894b1876509d78b4cd9268149b9ab165da9a31a6251d2448261fd99d1a7d22133bb3ef018493849f4a7896993");

        MyOkHttpUtils.getServiceDatas(map, Contents.KVB_CHECKSMSCODE, new MyOkHttpUtils.ServiceStatus() {
            @Override
            public void success(String response, int d) {
                if (response != null) {
                    JsonAnalysisModel jam = JsonAnalysisUtils.jsonAnalysis(response, CurrencyModel.class);
                    if (jam.isSuccess()) {
                        kvbOpenAccountActivity.makeProgress(2);
//                        openKvbAccount();
                    } else {
                        ToastUtils.showToast("请核对验证码！");
                    }
                }
                loadingDialog.dismiss();
            }

            @Override
            public void faild(Call call, Exception e, int id) {
                loadingDialog.dismiss();
            }
        });
    }

    class MyCountDownTimer extends CountDownTimer {

        MyCountDownTimer(long millisInfuture, long countDownInterval) {
            super(millisInfuture, countDownInterval);
        }

        @Override
        public void onTick(long millisUntilFinished) {
            get_code_textview.setEnabled(false);
            get_code_textview.setTextColor(resources.getColor(R.color.prompt_gray));
            get_code_textview.setText(millisUntilFinished / 1000 + "s");
        }

        @Override
        public void onFinish() {
            get_code_textview.setEnabled(true);
            get_code_textview.setTextColor(resources.getColor(R.color.kvb_account));
            get_code_textview.setText("重新获取");
        }
    }


    /**
     * 上传开户信息
     */
    public void openKvbAccount() {
        loadingDialog.show();
        File file = new File(frontImg);
        File file2 = new File(backImg);
        Map<String, Object> params = new HashMap<>();
        params.put("telephone", telephone);
        params.put("name", name);
        params.put("identity", identity);
        params.put("smsCode", smsCode);
        params.put("email", email);
        params.put("address", address);
        params.put("name", name);
        params.put("password", password);
        params.put("userId", spImp.getUserId());
        params.put("accessToken", "d31303049b7224712b2073354d4cc92c8a196f1894b1876509d78b4cd9268149b9ab165da9a31a6251d2448261fd99d1a7d22133bb3ef018493849f4a7896993");


        OkHttpUtils.post()//
                .addFile("frontImg", frontName, file)//
                .addFile("backImg", backName, file2)//
                .url(Contents.KVB_OPENACCOUNT)
                .params(params)//
                .build()//
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Loger.e("onError", id);
                        ToastUtils.showToast("网络异常");
                        loadingDialog.dismiss();
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        Loger.e("response", response);
                        JsonAnalysisModel jam = JsonAnalysisUtils.jsonAnalysis(response, OpenKVBModel.class);
                        if (jam.isSuccess()) {
                            OpenKVBModel model = (OpenKVBModel) jam.getData();
                            kvbOpenAccountActivity.openSuccess(model.getData().getAccount(),model.getData().getPassword());
                        }else{
                            ToastUtils.showToast(jam.getMsg());
                        }
                        loadingDialog.dismiss();
                    }
                });
    }
}
